//
//  EditAddressController.swift
//  AdressBook
//
//  Created by admin on 16/1/22.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit
class EditAddressController: UIViewController,UIAlertViewDelegate {
    @IBOutlet weak var nameTextfield: UITextField!
    @IBOutlet weak var addressTextfield: UITextField!
    @IBOutlet weak var down: UIBarButtonItem!
    weak var address:Address! // 当前修改的模型
    weak var editAddressDelegate:EditAddressControllerDelegate!// 代理
    override func viewDidLoad() {
        self.nameTextfield.text = address.name as String
        self.addressTextfield.text = address.address as String
    }
    // 保存修改之后的数据
    @IBAction func saveAddress(sender: UIBarButtonItem) {
        // 更改模型数据
        self.address.name = self.nameTextfield.text! as String
        self.address.address = self.addressTextfield.text! as String
        // 执行代理方法
        self.editAddressDelegate?.ediitAddressSaveButonClicked?(self.address)
        // 返回控制器
        self.navigationController?.popViewControllerAnimated(true)
    }
    // 判断用户修改改变确认按钮可用性
    @IBAction func checkAddress(sender: UITextField) {
        if nameTextfield.text != "" && addressTextfield.text != "" && nameTextfield.text != self.address.name && addressTextfield.text != self.address.address
        {
            down.enabled = true
        }
        else
        {
            down.enabled = false
        }
    }
    // 退出按钮事件
    @IBAction func cancel(sender: UIBarButtonItem) {
        if self.down.enabled
        {
            // 使用 UIAlertView 会有警告，所以改用 UIAlertController 了
            
//            let alert = UIAlertView(title: "确认放弃修改么?", message: "确认放弃修改么?", delegate: self, cancelButtonTitle: "继续修改", otherButtonTitles:"放弃修改")
//            alert.delegate = self
//            alert.show()
            // 使用 UIAlertController
            let alert = UIAlertController(title: "确认放弃修改么?", message: "确认放弃修改么?", preferredStyle: UIAlertControllerStyle.Alert)
            // 添加按钮
            alert.addAction(UIAlertAction(title: "放弃修改", style: UIAlertActionStyle.Destructive, handler: {
                alert in
                self.navigationController?.popViewControllerAnimated(true)
            }))
            // 添加按钮
            alert.addAction(UIAlertAction(title: "继续修改", style: UIAlertActionStyle.Destructive, handler: nil))
            // 显示
            self.view.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
        }
        else
        {
            self.navigationController?.popViewControllerAnimated(true)
        }
        
    }
    // UIAlertView 代理方法
    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        if buttonIndex == 1
        {
            self.navigationController?.popViewControllerAnimated(true)
        }
    }
}
// 修改address代理协议
@objc protocol EditAddressControllerDelegate
{
    optional func ediitAddressSaveButonClicked(address:Address)
}
